package com.resou.reader.mine.vipcenter.vipCenter;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.resou.reader.R;
import com.resou.reader.api.ApiConstant;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.api.entry.MetMealBean;
import com.resou.reader.api.entry.PrivilegeBean;
import com.resou.reader.api.entry.UserInfoBean;
import com.resou.reader.api.entry.WXPayBean;
import com.resou.reader.assist.WebActivity;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.commom.Constant;
import com.resou.reader.data.vip.model.VipPrivilege;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.mine.login.LoginActivity;
import com.resou.reader.mine.login.LoginFragment;
import com.resou.reader.mine.paycenter.PayCenterActivity;
import com.resou.reader.mine.paycenter.PayResult;
import com.resou.reader.mine.vipcenter.adapter.VipCenterAdapter;
import com.resou.reader.mine.vipcenter.adapter.VipMetMealAdapter;
import com.resou.reader.mine.vipcenter.paysuccess.PaySuccessActivity;
import com.resou.reader.mine.vipcenter.payview.IPayMethodListener;
import com.resou.reader.mine.vipcenter.payview.PayBootomDialog;
import com.resou.reader.reader.utils.ViewUtils;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.utils.log.LogUtil;
import com.resou.reader.view.CircleImageView;
import com.resou.reader.view.Loading;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.resou.reader.commom.Constant.WX_PAY_SUCCESS;

/**
 * 会员中心
 */
public class VipCenter extends ResouBaseActivity<VipCenterPresenter> implements IVipCenterContract.IVipCenterView, BaseQuickAdapter.OnItemChildClickListener, IPayMethodListener {
    private static final String TAG = "VipCenter";

    /**
     * 启动会员中心
     *
     * @param context
     */
    public static void start(Context context) {
        Intent starter = new Intent(context, VipCenter.class);
        context.startActivity(starter);
    }

    /**
     * 启动会员中心
     *
     * @param context
     */
    public static void start(Context context, boolean isShowHeader) {
        Intent starter = new Intent(context, VipCenter.class);
        starter.putExtra("isShowHeader", isShowHeader);
        context.startActivity(starter);
    }

    @BindView(R.id.tvTitle)
    TextView tvTitle;

    @BindView(R.id.mCircleImageView)
    CircleImageView mCircleImageView;
    @BindView(R.id.tvUserName)
    TextView tvUserName;
    @BindView(R.id.ivVipIcon)
    ImageView ivVipIcon;
    @BindView(R.id.rlHeaderContent)
    RelativeLayout rlHeaderContent;
    @BindView(R.id.tvVIPInfo)
    TextView tvVIPInfo;
    @BindView(R.id.llEmpty)
    RelativeLayout llEmpty;
    @BindView(R.id.mScrollView)
    ScrollView mScrollView;
    @BindView(R.id.tvVIPOnclick)
    TextView tvVIPOnclick;
    @BindView(R.id.tvVIPTime)
    TextView tvVIPTime;
    @BindView(R.id.rlHeader)
    RelativeLayout rlHeader;
    @BindView(R.id.tvPrivilegeLabel)
    TextView tvPrivilegeLabel;
    @BindView(R.id.rvVipPrivilege)
    RecyclerView rvVipPrivilege;
    @BindView(R.id.tvMore)
    TextView tvMore;
    @BindView(R.id.rvSetMeal)
    RecyclerView rvSetMeal;
    @BindView(R.id.cbAutoRenewal)
    CheckBox cbAutoRenewal;
    @BindView(R.id.tvInfo)
    TextView tvInfo;
    @BindView(R.id.btnPay)
    Button btnPay;
    VipCenterAdapter vipCenterAdapter;
    VipMetMealAdapter vipMetMealAdapter;

    boolean isAutoRecharge = true;
    boolean isShowHeader = true;
    int pos = 1;
    String coupont = "";
    /**
     * 支付底部弹框
     */
    PayBootomDialog payBootomDialog;
    PayBootomDialog.Builder builder;
    /**
     * 微信
     */
    private IWXAPI mWXAPI;
    AlertDialog alertDialog;
    List<VipPrivilege.PackageDataBean> listbeans;

    @Override
    public int getLayoutId() {
        return R.layout.activity_vip_center;
    }

    @Override
    public void retryRefreshData() {
        initData();
    }

    @Override
    protected void initStatusBar() {

    }

    @Override
    protected void initPresenter() {
        mPresenter = new VipCenterPresenter(this);
    }

    @Override
    protected void initView() {
        isShowHeader = getIntent().getBooleanExtra("isShowHeader", true);
        tvTitle.setText("会员中心");
        if (1 == UserInstance.getLoginData().getIsVipUser() || 2 == UserInstance.getLoginData().getIsVipUser()) {
            pos = 0;
        } else {
            pos = 1;
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        /**
         *特权显示
         */
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvVipPrivilege.setLayoutManager(linearLayoutManager);
        vipCenterAdapter = new VipCenterAdapter(R.layout.adapter_privilege, null);
        rvVipPrivilege.setAdapter(vipCenterAdapter);

        /**
         * VIP套餐
         */

        vipMetMealAdapter = new VipMetMealAdapter(R.layout.adapter_vip_metmeal, mPresenter.quearMetMeal());
        rvSetMeal.setLayoutManager(new LinearLayoutManager(this));
        rvSetMeal.setNestedScrollingEnabled(false);
        rvSetMeal.setAdapter(vipMetMealAdapter);
        vipMetMealAdapter.setOnItemChildClickListener(this);

        /**
         * 支付弹窗
         */
        builder = new PayBootomDialog.Builder(this).setiPayMethodListener(this);
        payBootomDialog = builder.create();
        mWXAPI = WXAPIFactory.createWXAPI(this, Constant.APP_ID_WE_CHAT, false);
        mWXAPI.registerApp(Constant.APP_ID_WE_CHAT);

        // 统计进入支付页面
        MobclickAgent.onEvent(this, "enter_pay", "进入支付页面");
        //注册微信支付的广播，以便处理相关操作
        registerReceiver(mReceiver, new IntentFilter(WX_PAY_SUCCESS));
        if (UserInstance.isTourist()) {
            PushAgent.getInstance(this).onAppStart();
            initDialog();
        }
    }

    @OnClick({R.id.ivBack, R.id.tvVIPOnclick, R.id.cbAutoRenewal, R.id.btnPay, R.id.tvMore})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.cbAutoRenewal:
                break;
            case R.id.btnPay:
                if (!NetworkUtils.isNetworkConnected(this)) {
                    ToastUtil.makeShortToast("网络异常");
                    return;
                }
                if (UserInstance.isTourist() && alertDialog != null) {
                    alertDialog.show();
                    return;
                }
                if (null != mPresenter.quearMetMeal() && !mPresenter.quearMetMeal().isEmpty())
                {
                    builder.setmAmount(mPresenter.quearMetMeal().get(pos).getActivity_price() + "").create();
                }
                payBootomDialog.showDialog();
                break;
            case R.id.tvVIPOnclick:
            case R.id.tvMore:
                if (isNetwork()) {
                    WebActivity.startActivity(this, ApiConstant.VIPDESCRIBEGUIDE, "会员说明");
                }
                break;
        }
    }

    @Override
    public void initData() {
        if (isShowHeader) {
            mPresenter.quearUserInfo();
            rlHeaderContent.setVisibility(View.VISIBLE);
        } else {
            rlHeaderContent.setVisibility(View.GONE);
            tvTitle.setText("立即开通");

        }
        mPresenter.quearPrivilege();
    }

    @Override
    public void showContent() {
        dissLoading();
    }

    @Override
    public void showProgress() {
        showLoading();
    }

    @Override
    public void showError(Throwable throwable) {
        ToastUtil.makeShortToast("网络异常");
        dissLoading();
        showNetErrorView(R.id.rlContent);
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        pos = position;
        switch (view.getId()) {
            case R.id.rlOnclick:
                vipMetMealAdapter.setNewData(mPresenter.calcMetMealCheck(adapter.getData(), position));
                break;
            case R.id.cbCheckBox:
                vipMetMealAdapter.setNewData(mPresenter.calcMetMealCheck(adapter.getData(), position));
                break;
        }
    }


    @Override
    public void showCoupont(List<VipPrivilege.PackageDataBean> list) {
        listbeans = list;
        vipMetMealAdapter.setNewData(mPresenter.calcMetMealCheck(list, pos));
        mScrollView.setVisibility(View.VISIBLE);
        llEmpty.setVisibility(View.GONE);
    }

    /**
     * 设置用户信息
     *
     * @param userInfoBean
     */
    @Override
    public void showUserInfo(UserInfoBean userInfoBean) {
        RequestOptions options = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .format(DecodeFormat.PREFER_RGB_565);
        Glide.with(this).load(userInfoBean.getU().getHead_pic() + "").apply(options).into(mCircleImageView);
        tvUserName.setText(userInfoBean.getU().getNickName() + "");
        if (userInfoBean.getU().isVipUser() == 1) {
            ivVipIcon.setVisibility(View.VISIBLE);
            ivVipIcon.setImageResource(R.mipmap.ic_vip_iconed);
            tvVIPInfo.setText("已开通包月VIP");
            tvVIPTime.setText("包月VIP特权中，剩余" + "天");
            int day = DateUtils.getDateDay2((userInfoBean.getU().getVipEndTime()));
            mPresenter.setTimeColor(tvVIPTime, "包月VIP特权中，剩余" + day + "天", day + "");
            rlHeader.setBackgroundResource(R.mipmap.ic_vip_headercard);
            if (new Date().getTime() > Long.valueOf(userInfoBean.getU().getVipEndTime())) {
                ivVipIcon.setImageResource(R.mipmap.ic_vip_icon);
                tvVIPInfo.setText("您的包月VIP已过期");
                tvVIPTime.setText("包月VIP，海量好书免费阅读");
            }
        } else {
            ivVipIcon.setVisibility(View.GONE);
            tvVIPInfo.setText("未开通包月VIP");
            tvVIPTime.setText("包月VIP，海量好书免费阅读");
            rlHeader.setBackgroundResource(R.mipmap.ic_vip_header_pic_no);
        }
    }

    @Override
    public void showPrivilege(List<VipPrivilege.PrivilegeDataBean> list) {
        vipCenterAdapter.setNewData(list);
    }

    @Override
    public void showWXPayOrder(WXPayBean wxPayBean) {
        PayReq request = new PayReq(); //调起微信APP的对象
        if (wxPayBean == null) {
            DLog.d(PayCenterActivity.class.getSimpleName(), "wxPayBean == null!!");
            return;
        }
        request.appId = wxPayBean.getAppid();
        request.partnerId = wxPayBean.getMch_id();
        request.prepayId = wxPayBean.getPrepay_id();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayBean.getNonce_str();
        request.timeStamp = wxPayBean.getTimestamp();
        request.sign = wxPayBean.getSign();
        mWXAPI.sendReq(request);//发送调起微信的请求
    }

    @Override
    public void goPaySuccessPage() {
        if (listbeans != null) {
            PaySuccessActivity.start(VipCenter.this, listbeans.get(pos).getVoucher() + "");
        } else {
            PaySuccessActivity.start(VipCenter.this, "0");
        }
    }

    @Override
    public void showAliPayOrder(String orderInfo) {
        Observable.create(new Observable.OnSubscribe<PayResult>() {
            @Override
            public void call(Subscriber<? super PayResult> subscriber) {
                PayTask alipay = new PayTask(VipCenter.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                subscriber.onNext(new PayResult(result));
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PayResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d(TAG, e.getMessage());
                    }

                    @Override
                    public void onNext(PayResult payResult) {
                        LogUtil.d(TAG, payResult.getResult());
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为9000则代表支付成功
                        if (android.text.TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                            ToastUtil.makeLongToast("支付成功");
                            /**
                             * 要判断如果不是首充，
                             */
                            mPresenter.updataVIPState();
                        } else if (android.text.TextUtils.equals(resultStatus, "4000")) {
                            ToastUtil.makeLongToast("支付失败");
                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        } else if (android.text.TextUtils.equals(resultStatus, "6001")) {
                            ToastUtil.makeLongToast("支付取消");
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            ToastUtil.makeLongToast("网络连接出错");
                        }
                    }
                });
    }

    @Override
    public AppCompatActivity getViewContext() {
        return this;
    }

    /**
     * 接收微信支付成功后的广播
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(VipCenter.this, "支付成功", Toast.LENGTH_SHORT).show();
            mPresenter.updataVIPState();

        }
    };

    /**
     * 支付宝支付
     */
    @Override
    public void setIAliPayOnclickListener() {
        mPresenter.quaerAliPayOrderInfo(mPresenter.quearMetMeal().get(pos).getActivity_price() + "",
                mPresenter.quearMetMeal().get(pos).getId(), listbeans.get(pos).getVoucher() + "");
    }

    /**
     * 微信支付
     */
    @Override
    public void setIWXPayOnClickListener() {
        mPresenter.quaerWXPayOrderInfo(mPresenter.quearMetMeal().get(pos).getActivity_price() + "",
                mPresenter.quearMetMeal().get(pos).getId(), listbeans.get(pos).getVoucher() + "");
    }

    @Override
    protected void onPause() {
        super.onPause();
        payBootomDialog.dissDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    /**
     * 是否游客访问弹窗
     */
    private void initDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_vip, null);
        TextView tvLogin = view.findViewById(R.id.tvLogin);
        TextView tvNo_LoginLook = view.findViewById(R.id.tvNo_LoginLook);
        TextView tvCancell = view.findViewById(R.id.tvCancell);
        AlertDialog.Builder build = new AlertDialog.Builder(this);
        build.setView(view);

        alertDialog = build.create();
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
//                LoginFragment.getInstance().setLoginListener(loginListener);
//                LoginFragment.getInstance().show(getSupportFragmentManager(), "LoginFragment");
                LoginActivity.start(VipCenter.this);
            }
        });
        tvNo_LoginLook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                if (mPresenter.quearMetMeal() == null) {
                    return;
                }
                builder.setmAmount(mPresenter.quearMetMeal().get(pos).getActivity_price() + "").create();
                payBootomDialog.showDialog();
            }
        });
        tvCancell.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(VipPrivilege event) {
        if (1 == UserInstance.getLoginData().getIsVipUser() || 2 == UserInstance.getLoginData().getIsVipUser()) {
            pos = 0;
        } else {
            pos = 1;
        }
        mPresenter.quearPrivilege();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        mPresenter.quearUserInfo();
        mPresenter.quearMetMeal();
    }
}
